import { useState, useEffect } from 'react';
import { Table, message, Select, Space, Button, Form, Input } from 'antd';
const { Option } = Select;
import { laboratoryService } from '@/service';
import { executeActionAfterReq } from '@/util/errorHandle';
import styles from './index.less';

function LaboratoryPage() {
  const [canChange, setCanChange] = useState(true);
  const [showDialog, setShowDialog] = useState(false);
  const [action, setAction] = useState('NONE');
  const [laboratoryData, setLaboratoryData] = useState([]);
  useEffect(() => {
    getAllLaboratory();
  }, []);

  const getAllLaboratory = async () => {
    const res = await laboratoryService.getAllLaboratory().catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, () => {
      setLaboratoryData(res?.data);
    })
  }

  const columns = [
    {
      title: '实验室号',
      dataIndex: 'lId',
      key: 'lId',
      sorter: (a: any, b: any) => a.lId - b.lId,
      sortDirections: ['ascend'],
    },
    {
      title: '实验室地点',
      dataIndex: 'location',
      key: 'location',
    },
    {
      title: '实验室容量',
      dataIndex: 'capacity',
      key: 'capacity',
    },
    {
      title: '是否可用',
      dataIndex: 'available',
      key: 'available',
      render: (text: any) => <>{text == 0 ? '不可用' : '可用'}</>,
    },
    {
      title: '操作',
      key: 'action',
      render: (text: any, record: any) => (
        <Space size="middle">
          <Button type="link" size ="small" className={styles.link} onClick={() => handleEdit(record)}>修改</Button>
          <Button type="link" size ="small" className={styles.link} onClick={() => handleDel(record)} danger>删除</Button>
          <Button type="link" size ="small" className={styles.link} onClick={() => handleForbid(record)} danger>禁用</Button>
        </Space>
      ),
    },
  ];

  const [form] = Form.useForm();
  form.setFieldsValue({});
  
  const handleEdit = (record: any) => {
    setCanChange(false);
    form.resetFields();
    form.setFieldsValue(record);
    setShowDialog(true);
    setAction('EDIT');
  }
  const handleForbid = async (record: any) => {
    record.available = 0;
    const res = await laboratoryService.updateLaboratory(record).catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, async () => {
      message.info('禁止成功');
      await getAllLaboratory();
    })
  }
  const handleDel = async (record: any) => {
    const res = await laboratoryService.destroyLaboratory(record).catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, async () => {
      message.info('删除成功');
      await getAllLaboratory();
    })
  }
  const handleAdd = () => {
    setCanChange(true);
    form.resetFields();
    setShowDialog(true);
    setAction('ADD');
  }
  const handleCancel = () => {
    setShowDialog(false);
  }
  const handleSubmit = async (values: any) => {
    if (action === 'EDIT') {
      const res = await laboratoryService.updateLaboratory(values).catch(() => {
        message.error('请求错误');
      });
      executeActionAfterReq(res, async () => {
        message.info('修改成功');
        await getAllLaboratory();
        setShowDialog(false);
      })
    } else if (action === 'ADD') {
      const res = await laboratoryService.appendLaboratory(values).catch(() => {
        message.error('请求错误');
      });
      executeActionAfterReq(res, async () => {
        message.info('添加成功');
        await getAllLaboratory();
        setShowDialog(false);
      })
    } else {
      message.error('指定动作错误');
    }
  }
  const onAvailableChange = (value: string | number) => {
    form.setFieldsValue({
      available: Boolean(value),
    });
  }
  
  return (
    <div className={styles.laboratory}>
      <Button type="primary" className={styles.add} onClick={handleAdd}>添加实验室</Button>
      <Table dataSource={laboratoryData} columns={columns} style={{minHeight: "400px"}} />
      <div className={styles.formdiv} style={{display: showDialog ? 'block' : 'none'}}>
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 10 }}
          form={form}
          autoComplete="off"
          onFinish={handleSubmit}
          className={styles.form}
        >
          <Form.Item label="实验室号" name="lId" rules={[{ required: true }]}>
            <Input disabled={!canChange} />
          </Form.Item>
          <Form.Item label="实验室地点" name="location" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item label="实验室容量" name="capacity" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item label="是否可用" name="available">
            <Select
              placeholder="请选择"
              onChange={onAvailableChange}
            >
              <Option value={false}>不可用</Option>
              <Option value={true}>可用</Option>
            </Select>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 10 }}>
            <Button type="primary" htmlType="submit">
              确认
            </Button>
            <Button type="link" htmlType="button" onClick={handleCancel}>
              取消
            </Button>
          </Form.Item>
        </Form>
        <div className={styles.cover} onClick={handleCancel}></div>
      </div>
    </div>
  );
}

export default LaboratoryPage;
